package com.alog.yzd.jdbc.hm;

import com.alog.yzd.jdbc.User;

import java.sql.*;
import java.util.List;

abstract public class AbstractDao {
    protected Object find(String sql, List<Object> params){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            conn = JdbcUtils2.getConnction();
            ps = conn.prepareStatement(sql);
            int index = 1;
            if(params != null && !params.isEmpty()){
                for(Object obj : params){
                    ps.setObject(index++, obj);
                }
            }
            rs = ps.executeQuery();
            Object obj = null;
            while (rs.next()){
                obj = rowMapper(rs);
            }
            return obj;
        } catch(SQLException e){
            throw new DaoException(e.getMessage(), e);
        } finally {
            JdbcUtils2.release(rs, ps, conn);
        }
    }

    abstract protected Object rowMapper(ResultSet rs) throws SQLException;

    protected int update(String sql, List<Object> params) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            conn = JdbcUtils2.getConnction();
            ps = conn.prepareStatement(sql);
            int index = 1;
            if(params != null && !params.isEmpty()){
                for(Object obj : params){
                    ps.setObject(index++, obj);
                }
            }
            int i = ps.executeUpdate();
            return i;
        } catch(SQLException e){
            throw new DaoException(e.getMessage(), e);
        } finally {
            JdbcUtils2.release(rs, ps, conn);
        }
    }

//    public int insert(String sql, List<Object> params) {
//        Connection conn = null;
//        PreparedStatement ps = null;
//        ResultSet rs = null;
//        try{
//            conn = JdbcUtils2.getConnction();
//            ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
//            int index = 1;
//            if(params != null && !params.isEmpty()){
//                for(Object obj : params){
//                    ps.setObject(index++, obj);
//                }
//            }
//            ps.executeUpdate();
//            rs = ps.getGeneratedKeys();
//            int i = rs.getInt(1);
//            return i;
//        } catch(SQLException e){
//            throw new DaoException(e.getMessage(), e);
//        } finally {
//            JdbcUtils2.release(rs, ps, conn);
//        }
//    }
}
